package com.es.trie;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author 二十
 * @since 2022/1/20 8:25 上午
 */
public class Trie extends AbstractTrie {

    private class TrieNode {

        boolean isWord;

        Map<Character, TrieNode> next = new TreeMap<>();

        public TrieNode(boolean isWord) {
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public TrieNode() {
            this(false);
        }
    }

    private TrieNode root;

    private int size;

    public Trie() {
        root = new TrieNode();
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void add(String word) {
        addNR(word);
    }

    private void addNR(String word) {
        TrieNode pointer = root;
        for (int i = 0; i < word.length(); i++) {
            char tmp = word.charAt(i);
            if (!pointer.next.containsKey(tmp)) {
                pointer.next.put(tmp, new TrieNode());
            }
            pointer = pointer.next.get(tmp);
        }
        if (!pointer.isWord) {
            pointer.isWord = true;
            size++;
        }
    }


    @Override
    public boolean contains(String word) {
        TrieNode p = root;
        for (int i = 0; i < word.length(); i++) {
            char t = word.charAt(i);
            if (!p.next.containsKey(t)) {
                return false;
            }
            p = p.next.get(t);
        }
        return p.isWord;
    }

    @Override
    public boolean isPrefix(String prefix) {
        TrieNode p = root;
        for (int i = 0; i < prefix.length(); i++) {
            char t = prefix.charAt(i);
            if (!p.next.containsKey(t)) {
                return false;
            }
            p = p.next.get(t);
        }
        return true;
    }


}
